#include "SharedVariables.fxh"

float3 lightDirection;
float3 lightColor;
float lightIntensity = 1.0f;

float3 cameraPosition;
float4x4 InverseViewProj;

sampler depthSampler = sampler_state
{
	Texture=(DepthRT);
	MAGFILTER = POINT;
	MINFILTER = POINT;
	MIPFILTER = POINT;
	AddressU = Clamp;
	AddressV = Clamp;
};

sampler diffuseSampler = sampler_state
{
	Texture=(DiffuseRT);
	MAGFILTER = POINT;
	MINFILTER = POINT;
	MIPFILTER = POINT;
	AddressU = Clamp;
	AddressV = Clamp;
};

sampler normalSampler = sampler_state
{
	Texture=(NormalRT);
	MAGFILTER = POINT;
	MINFILTER = POINT;
	MIPFILTER = POINT;
	AddressU = Clamp;
	AddressV = Clamp;
};

struct DirectionalVSInput
{
    float3 Position : POSITION0;
    float2 TexCoord : TEXCOORD0;
};

struct DirectionalVSOutput
{
    float4 Position : POSITION0;
    float2 TexCoord : TEXCOORD0;
};

DirectionalVSOutput DirectionalVS(DirectionalVSInput input)
{
    DirectionalVSOutput output;

    output.Position = float4(input.Position, 1);
    output.TexCoord = input.TexCoord - halfPixel;

    return output;
}

float4 DirectionalPS(DirectionalVSOutput input) : COLOR0
{
	float4 normalData = tex2D(normalSampler, input.TexCoord);
	float3 normal = (2.0f * normalData.xyz) - 1.0f;
	float specularPower = normalData.a * 255;
	float4 diffuseData = tex2D(diffuseSampler, input.TexCoord);
	float3 diffuseColor = diffuseData.rgb;
	float specularIntensity = diffuseData.a;
	float depthVal = tex2D(depthSampler, input.TexCoord).r;
	
	float4 position;
	position.x = (2.0f * input.TexCoord.x) - 1.0f;
	position.y = -((2.0f * input.TexCoord.x) - 1.0f);
	position.z = depthVal;
	position.w = 1.0f;
	
	position = mul(position, InverseViewProj);
	position /= position.w;
	
	float3 lightVector = -normalize(lightDirection);
	
	float NdL = max(0, dot(normal, lightVector));
	float3 diffuseLight = NdL * lightColor;
	
	float3 reflectionVector = normalize(reflect(lightVector, normal));
	float3 surfaceToCamera = normalize(cameraPosition - position);
	float specularLight = specularIntensity * pow(saturate(dot(reflectionVector, surfaceToCamera)), specularPower);
	
	return lightIntensity * float4(diffuseLight, specularLight);
}

technique DirectionalLight
{
	pass Pass0
	{
		VertexShader = compile vs_2_0 DirectionalVS();
		PixelShader = compile ps_2_0 DirectionalPS();
	}
}